//
//  ORsearchViewController.m
//  News
//
//  Created by rimi on 2016/12/8.
//  Copyright © 2016年 dongfumei. All rights reserved.
//

#import "ORsearchViewController.h"

#import "ORSearchDateViewController.h"
#import "ORDetailViewController.h"
#import "ShopHotTagCell.h"

@interface ORsearchViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,ShopHotTagCellDelegate>{
    id _oberver;
}

@property (nonatomic, strong) UITableView    *tableView;
@property (nonatomic, strong) UITextField    *searchField;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSArray        *arrayHot;

@property (nonatomic, strong) NSString *titleText;


@end

@implementation ORsearchViewController


#pragma mark -  初始化释放内存
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:_oberver];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView removeFromSuperview];
    
}


#pragma mark -
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor=[UIColor whiteColor];
    
    [self initializeAppearence];
    [self initWith];
    

    
}


- (void)initWith{
    
    _oberver = [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        
        if (self.searchField.text.length == 0) {
            
            [self.tableView removeFromSuperview];
        }else{
            
            [self.view addSubview:self.tableView];
        }
        
        [self initalizeDataSource:self.searchField.text];
    }];
   
    
}


-(void)initializeAppearence{
    
    self.arrayHot = [ORSingTO shareinfo].arrayTitle;
    self.navigationItem.titleView = self.searchField;
     self.dataSource = [NSMutableArray array];
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.tableView];
    
    
    ShopHotTagCell *shopView = [[ShopHotTagCell alloc] initWithDataSource:self.arrayHot];
    
    shopView.frame = AAdaptionRect(0, 50, kBaseWidth, 300);
    shopView.delegate=self;
//    [ShopHotTagCell cellHeightWithDataSource:sel  f.arrayHot];
    
    [self.view addSubview:shopView];
   
}

#pragma mark -  *** 热门搜索按钮详情 ***

- (void)hotTagDidSelectedWithTagName:(NSInteger )entity{
    
    ORDetailViewController *detail = [[ORDetailViewController alloc]init];
        NSDictionary *dic = self.arrayHot[entity];
    
        detail.url = dic[@"url"];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}


#pragma mark -  *** 搜索网络数据请求 ***
- (void)initalizeDataSource:(NSString *)str {
    
    NSString *url=@"http://apis.baidu.com/txapi/weixin/wxhot";
    NSLog(@"%@", self.searchField.text);
    NSDictionary *dic=@{@"num":@"10",@"rand":@"1",@"word":str,@"page":@"1"};
    
    AFHTTPSessionManager   *manager=[AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"b0468eba387fbccb6b770886063c9814" forHTTPHeaderField:@"apikey"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript",@"text/plain", nil];
    
    [manager GET:url parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//    NSLog(@"%@",responseObject);
    self.dataSource=responseObject[@"newslist"];
    dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableView reloadData];
        
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"%@",error.localizedDescription);
        
    }];
}

#pragma mark -  键盘响应

//某个字符转是否应该被输入
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if ([self.searchField.text isEqualToString:@"\n"]) {
        
    if (self.searchField.text.length == 0) {
        
        return NO;
        }
        
    self.searchField.text = @"";
    return NO;
    }else {
        return YES;
    }
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.searchField resignFirstResponder];
    
}



#pragma mark -  UITextFieldDelegate;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    _tableView.hidden = NO;
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.searchField resignFirstResponder];
    return YES;
}

#pragma mark -  *** UITableViewDelegate,UITableViewDataSource, ***
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static  NSString  *string=@"SerUITableViewCell";
    UITableViewCell  *cell=[tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:string];
    }
    
    cell.textLabel.text=self.dataSource[indexPath.row][@"title"];
    return cell;
}


#pragma mark -  ***  tableViewDelegate ***

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.searchField resignFirstResponder];
    self.searchField.text = @"";
    
    ORSearchDateViewController  *vc=[[ORSearchDateViewController alloc]init];
    NSString  *url=self.dataSource[indexPath.row][@"url"];
    vc.picUrl=url;
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}


#pragma mark - setter与getter

- (UITextField *)searchField
{
    if (!_searchField) {
        _searchField=[[UITextField alloc]initWithFrame:AAdaptionRect((750-630)/2, 100, kBaseWidth-80, 40)];
        _searchField.delegate=self;
        _searchField.backgroundColor=[UIColor whiteColor];
        _searchField.alpha=0.3;
        _searchField.layer.cornerRadius=10;
        _searchField.placeholder=@"请输入要查找的文字";
        [_searchField canBecomeFirstResponder];
        _searchField.font=[UIFont systemFontOfSize:15];
        _searchField.autocapitalizationType=UITextAutocapitalizationTypeNone;;
        _searchField.clearButtonMode=UITextFieldViewModeWhileEditing;
        _searchField.returnKeyType=UIReturnKeySearch;
        
    }
    return _searchField;
}


- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:AAdaptionRect(0, 0, kBaseWidth, kBaseHeight-150) style:UITableViewStylePlain];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.hidden = YES;
        _tableView.rowHeight=AAdaptation(80);
        _tableView.tableFooterView=[[UIView alloc]init];
    }
    return _tableView;
}

@end
